package top.yongyan0624.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import top.yongyan0624.common.lang.Result;
import top.yongyan0624.entity.NannyType;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yongyan
 * @since 2021-12-29
 */
@RestController
@RequestMapping("/nanny/type")
public class NannyTypeController extends BaseController {
    @GetMapping("/list")
    public Result list(String name) {
        Page<NannyType> pageData = nannyTypeService.page(getPage(), new QueryWrapper<NannyType>()
                .like(StrUtil.isNotBlank(name), "name", name));

        return Result.success(pageData);
    }

    @PostMapping("/save")
    @PreAuthorize("hasRole('admin')")
    public Result save(@RequestBody NannyType nannyType) {

        NannyType type = nannyTypeService.getOne(new QueryWrapper<NannyType>().eq("name", nannyType.getName()));
        if (type != null) {
            return Result.fail("该保姆类型名已经存在");
        }
        //保存nannyType
        nannyTypeService.save(nannyType);

        return Result.success(nannyType);
    }

    @PostMapping("/update")
    @PreAuthorize("hasRole('admin')")
    public Result update(@RequestBody NannyType nannyType) {
        //修改nannyType
        nannyTypeService.updateById(nannyType);

        return Result.success(nannyType);
    }

    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasRole('admin')")
    public Result delete(@RequestBody Long[] ids) {
        nannyTypeService.removeByIds(Arrays.asList(ids));

        return Result.success("删除成功");
    }
}
